package com.cherry.androidcode.mvp1

/**
 * 第一重代理->代理对象->ProxyMvpCallback(实现目标接口),直接封装MVP实现
 * 持有目标对象引用->Activity
 * mvpCallback->本质就是Actiivty
 * @author DongMS
 * @since 2019/7/11
 */
class ProxyMVPCallback<V : BaseView, P : BasePresenter<V>>(private val mvpCallback: MVPCallback<V, P>) : MVPCallback<V, P> {

    override var mvpPresenter: P?
        get() = mvpCallback.mvpPresenter
        set(value) {
            mvpCallback.mvpPresenter = value
        }


    override var mvpView: V?
        get() = mvpCallback.mvpView
        set(value) {
            mvpCallback.mvpView = value
        }


    override fun createPresenter(): P? {
        var presenter: P? = mvpCallback.mvpPresenter
        if (presenter == null) {
            presenter = mvpCallback.createPresenter()
        }
        if (presenter == null) {
            throw NullPointerException("create BasePresenter is not null!")
        }

        // 绑定
        mvpCallback.mvpPresenter = presenter
        return presenter
    }

    override fun createView(): V? {
        var view: V? = mvpCallback.mvpView
        if (view == null) {
            view = mvpCallback.createView()
        }
        if (view == null) {
            throw NullPointerException("create BaseView is not null!")
        }

        // 绑定
        mvpCallback.mvpView = view
        return view
    }

    fun attachView() {
        mvpPresenter?.attachView(mvpView
                ?: throw NullPointerException("attach BaseView is not null!"))
    }

    fun detachView() {
        mvpPresenter?.detachView()
    }
}